package org.hot100_1;

public class leetcode93 {
    //三指针
    public void sortColors(int[] nums) {
        int len = nums.length;
        if (len<2){
            return;
        }
        // 0的范围：[0,zeroIndex)
        // 1的范围：[zeroIndex,twoIndex)
        // 2的范围：[twoIndex,len-1]
        int zeroIndex = 0;
        int twoIndex = len;
        int i = 0;
        while (i<twoIndex){
            if (nums[i]==0){
                swap(nums,i,zeroIndex);
                zeroIndex++;
                i++;
            }else if (nums[i]==2){
                //使用twoIndex-1的原因：twoIndex-1是没有被遍历的数据，而twoIndex是以及遍历的数据，为2
                swap(nums,i,twoIndex-1);
                twoIndex--;
            }else {
                i++;
            }
        }

    }

    private void swap(int[] nums, int index1, int index2) {
        int temp = nums[index1];
        nums[index1] = nums[index2];
        nums[index2] = temp;
    }
}
